import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let lifeData = {}

try {
  lifeData = uni.getStorageSync('lifeData')
} catch(e) {
  
}

let saveStateKeys = ['vuex_user','info','couponsNum','userInfos','tjs','zqLists','sessionId','currentDatas','agents','numTotal']

const saveLifeData = function(key, value) {
  if (saveStateKeys.indexOf(key) != -1) {
    let tmpLifeData = uni.getStorageSync('lifeData')
    tmpLifeData = tmpLifeData ? tmpLifeData : {},
    tmpLifeData[key] = value
    uni.setStorageSync('lifeData', tmpLifeData)
  }
}

const store = new Vuex.Store({
  state: {
    vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {name: ''},
    vuex_version: "1.0.0",
    vuex_custom_nav_bar: true,
    vuex_status_bar_height: 0,
    vuex_custom_bar_height: 0,
	userInfos:lifeData.userInfos ? lifeData.userInfos : {},
	info: lifeData.info ? lifeData.info : {},
	couponsNum: lifeData.couponsNum ? lifeData.couponsNum : {},
	tjs: lifeData.tjs ? lifeData.tjs : {},
	zqLists:lifeData.zqLists ? lifeData.zqLists : {},
	sessionId: lifeData.sessionId ? lifeData.sessionId : {},
	setGoodsShelves:[],
	currentDatas:lifeData.currentDatas ? lifeData.currentDatas : {},
	agents: lifeData.agents ? lifeData.agents : {},
	numTotal:lifeData.numTotal ? lifeData.numTotal : 0,
	
  },
  mutations: {
    $tStore(state, payload) {
      // 判断是否多层调用，state中为对象存在的情况，例如user.info.score = 1
      let nameArr = payload.name.split('.')
      let saveKey = ''
      let len = nameArr.length
      if (len >= 2) {
        let obj = state[nameArr[0]]
        for (let i= 1; i < len - 1; i++) {
          obj = obj[nameArr[i]]
        }
        obj[nameArr[len - 1]] = payload.value
        saveKey = nameArr[0]
      } else {
        // 单层级变量
        state[payload.name] = payload.value
        saveKey = payload.name
      }
      
      // 保存变量到本地中
      saveLifeData(saveKey, state[saveKey])
    }
  },
  actions: {
  }
})

export default store